<?php

/**
 *类名：applePayTrade.php
 *功能  apple交易返回
 *版本：1.0
 *日期：2016-06-26
'说明：
 */
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set('Asia/Shanghai');
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');
set_time_limit(0);

//include_once("./IapppayCpSyncForPHP/base.php");
//include_once("./IapppayCpSyncForPHP/config.php");
include_once("./connConfig.php");
include_once("./mysql.class.php");
include_once("./redis.class.php");
include_once("./httpclient.php");

include_once("./logger.php");


//file_put_contents('./text.txt',date('Y-m-d',time()).'---'.json_encode($_REQUEST['param']).''.PHP_EOL,FILE_APPEND);

function recv_post_data() {
	//$PostData = file_get_contents("php://input") ? file_get_contents("php://input") : gzuncompress($GLOBALS['HTTP_RAW_POST_DATA']);
	return $_REQUEST['param'];

}

function record_post_data($PostData) {
    $date_dir = dirname(__FILE__).'/datalog/'.date('Y-m-d',time());
	if ( !is_dir( $date_dir ) ) {
        mkdir($date_dir, 0700);
    }
    file_put_contents($date_dir. '/' .rand(1000,9999). '-' .time(). '.txt', $PostData);
}

function parse_post_data($PostData) {
	global $platpkey;
	if(!parseResp($PostData, $platpkey, $respJson)) {
		echo "parse resp data failed!\n";
	}
	return $respJson;
}

function connect_db(&$redis, &$mysql, $uid) {
    $ret = $mysql->connect(Config::$mysql_config);
    if (!$ret) {
        echo("mysql connect error.\n");
        exit(0);
    }

    $ret = $redis->initCacheRedis();
    if (!$ret) {
        echo("cache redis connect error.\n");
        exit(0);
    }

    $ret = $redis->initDataRedis($uid);
    if(!$ret) {
        echo("data redis connect error.\n");
        exit(0);
    }
}




function insert_pay_record(&$mysql, $payInfArr) {
    //插入充值记录
    $payrecord = array();
    $payrecord['uid'] = (int)$payInfArr['uid'];
    $payrecord['rmb'] = (float)$payInfArr['price'];
	$payrecord['goodsid'] = (float)$payInfArr['goodsid'];
    $payrecord['vercode'] = $payInfArr['version'];
    $payrecord['order_id'] = $payInfArr['order_id'];
    $payrecord['type'] = 2;
    $payrecord['create_time'] = time();
    $mysql->insert('payrecord', $payrecord);
}

function sys_task_of_pay($uid,&$redis) {
    //首次冲值奖券任务是否完成
    //从奖券任务记录字段中获取奖券任务完成度
    $task_id = 2;//任务号为2
    $task_complete_record_str = $redis->data_redis->hget("hu:{$uid}", "coin_task_complete_record");
    $task_pieces = explode("|", $task_complete_record_str);
    $task_value = $redis->cache_redis->hget("hcointask:{$task_id}", "task_value");
    //如果任务完成度 < 最大任务完成值,则任务完成度加1
    if ((int)$task_pieces[$task_id - 1] < (int)$task_value) {
        $task_pieces[$task_id - 1] += 1;
        //重新组装，任务奖励记录字符串
        $size = count($task_pieces);
        $str = "";
        for ($i = 0; $i < $size; $i++) {
            $str .= $task_pieces[$i];
            if ($i < $size - 1) {
                $str .= "|";
            }
        }
        //重新设置任务奖励记录字符串
        $redis->data_redis->hset("hu:{$uid}", "coin_task_complete_record", $str);
    }
}
do_trade();
function do_trade() {
	$logger =  new Logger("./logs/yj.log");
	$apple_receipt =recv_post_data();
	//record_post_data($apple_receipt);
	$logger->info('客户端返回:', $apple_receipt);
	$apple_receipt = json_decode($apple_receipt,true);


	/*$apple_receipt=array(
		'orderinfo'=>'caaf4ebfcfb2db70dc3fed5b',
		'userid'=>100000,
		'isSuccess'=>1
	);*/
	
	//exit;
 /*   $userid = $apple_receipt['userid'];
	if($apple_receipt['isSuccess']==0){
		exit;
	}*/
	
	$redis = new RedisDriver();
    $mysql = new MysqlDriver();

    connect_db($redis, $mysql,$userid);

	$row = $mysql->select('applypay','*',array('order_id' =>$apple_receipt['orderinfo']));
	//var_dump($row);
	$logger->info('applePayTrade', '2');
    /*if ( count($row) == 0) {
        //echo("order not exist.\n");
        returnData(array(),588,'订单不存在');
		exit;
    }
	
	$goods = $mysql->select('goods','*',array('id' =>$row[0]['goods_id']));
	if ( count($goods) == 0) {
        //echo("order not exist.\n");
        returnData(array(),588,'商品不存在');
		exit;
    }
	$logger->info('applePayTrade', 'test11');
	$jsonData = array('receipt-data'=>$apple_receipt['identifier']);//这里本来是需要base64加密的，我这里没有加密的原因是客户端返回服务器端之前，已经作加密处理
	
	$jsonData = json_encode($jsonData);
	
	
	$url_zs = 'https://buy.itunes.apple.com/verifyReceipt';  //正式验证地址 21007
	$response_zs = http_post_data($url_zs,$jsonData);
	$status = $response_zs->status;
	$logger->info('status1',$status ); 
	//
	
	$url = 'https://sandbox.itunes.apple.com/verifyReceipt'; //测试验证地址 
	if($status==21007){
		$response = http_post_data($url,$jsonData);
		$status = $response->status; 
	}
	
	$logger->info('status', $status); 
	
	if($status == 0){

		$orderinfo = json_decode(json_encode($response),true);
		record_post_data(json_encode($response));

		$app = $orderinfo['receipt']['bid'];		//应用ID
		$item_id = $orderinfo['receipt']['item_id'];
		$transaction_id = $orderinfo['receipt']['transaction_id'];	//ios返回的支付成功的ID

		if($app!='com.xfgame.wxhh'){

			exit();

		}

		//检测商品是否正确
		$goods = $mysql->select('goods','*',array('apple_id' =>$item_id));
		$logger->info('test','10');
		if ( count($goods) == 0) {
			//echo("order not exist.\n");
			//returnData(array(),588,'商品存在');
			exit;
		}

		//检测订单是否已经充值成功过
		$app_orderid = $mysql->select('applypay','*',array('iap_transaction_id' =>$transaction_id ));
		
		$logger->info('app_orderid', $app_orderid);
		if(count($app_orderid)){
			exit;
		}


		$logger->info('applePayTrade', 'test');
        $payInfArr = $row[0];
        //var_dump($payInfArr);
        $uid = (int)$payInfArr['uid'];
		$price = (int)$payInfArr['price'];
		$goodsid = (int)$payInfArr['goods_id'];
        $is_send = (int)$payInfArr['is_send'];

		
       	if ($is_send == 1) {

		  returnData(array(),588,'订单已经支付');
		  exit;
        }
	   
		$data = array(
			'is_send' => 1,
			'type' => 1,
			'iap_transaction_id'=>$transaction_id,
			'update_time' => date('Y-m-d H:i:s',time()
		)
		);
		//$logger->info('applePayTrade', json_encode($data));
		//充值成功后改变状态；
        $mysql->update('applypay',$data,array('order_id' => $apple_receipt['orderinfo']) );;*/

		//处理充值，加金币或道具
		//$goodsid=$goods['id'];
		$goodsid=2;
		$uid=100011;

		$redis->initDataRedis($uid);
		$player = $redis->data_redis->hMGet("hu:{$uid}", array('id','user','exp', 'name', 'money', 'coin','isget_coin_task_reward_record'));
		//var_dump($player);

		if($goodsid==7 && $player['isget_coin_task_reward_record']==1){
			exit("你已经购买过此商品,不可购买");
		}

		//处理充值，加金币或道具
		$goodsadd = $redis->cache_redis->hMGet("hg:{$goodsid}", array("money","rmb","propnum","give_money"));
	//var_dump($goodsadd);
		$add_coin = (int)($goodsadd['money']);

		if($goodsid>=20 && $goodsid<30){
			$type=1;
			$proop_info=add_porp($goodsid,$uid ,$redis,(int)$player['money'],(int)$goodsadd['give_money'],$mysql,(int)$goodsadd['rmb']);
			//var_dump($proop_info);
		}

		if($goodsid>=30 && $goodsid<50){
			gift_pay($goodsid,$uid ,$redis,(int)$goodsadd['rmb'],$goodsadd['propnum']);
		}
		if($goodsid>=50){
			gift_money($goodsadd['give_money'],$mysql,$redis,$uid,$player['money'],(int)$goodsadd['rmb']);
		}
		if($goodsid<10){
			if($goodsid==7){
				$exp=10;
				$redis->data_redis->hSet("hu:{$uid}","isget_coin_task_reward_record",1);
			}else{
				$exp=(int)$goodsadd['rmb'];
			}

			//给用户加钻石
			$cur_coin = $redis->data_redis->hincrBy("hu:{$uid}","coin",$add_coin);

			//给用户加经验
			$redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
			$ret=$redis->data_redis->hMget("hu:{$uid}",array("coin","money","exp"));

			//var_dump($ret);
			//写入变化记录
			if($cur_coin){
				$info =array();
				$info['type'] = '6';
				$info['uid']    = $uid;
				$info['coin']  = $ret['coin'];
				$info['change_coin'] = $add_coin;
				$info['create_time']  = time();
				$mysql->insert("coin_change_rec",$info);//写入金币变化表；
			}else{
				$this->returnData(array(),588,'redis写入失败');
			}
		}


		//插入充值记录
		$pyinfo = array('uid'=>$uid,'price'=>$price,'goodsid'=>$goodsid);
		//$pyinfo = array('uid'=>$uid,'price'=>1,'goodsid'=>$goodsid);
		insert_pay_record($mysql,$pyinfo);


		$logger->info('applePayTrade', 'sucess');
	/*}else{

		$status = $response->status;
		$array =array('desc'=>'支付失败','ret'=>$status);

		echo json_encode($array);
		exit;
	}*/

	$logger->info('vip8-', json_encode($redis->data_redis->hMget("hu:$uid",array('is_vip','vip_time','id'))));
	//$num=$proop_info['num'];
	//$prop_id=$proop_info['prop_id'];

	$num=6;
	$prop_id=301;
	$http = new httpclient();
	if($goodsid<10){
		$type=2;
		$url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"coin":'.$ret['coin'].'}}';
	}else{
		$url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=PaySuccessResult&receiver='.$uid .'&param={"data_type":'.$type.',"data":{"prop_num":'.$num.',"prop_id":'.$prop_id.'}}';
	}
	echo $url;
    $logger->info('applePayTrade', $url);
	
	if(!$http->Get($url)){
		returnData(array(),588,'充值成功，将在下次登录显示！');
		exit;
	}



	$http->close();
	$redis->deinitDataRedis();
    $redis->deinitCacheRedis();
    $mysql->close();
	//curl请求苹果app_store验证地址
    exit;

}


//充值增加道具
function add_porp($goodsid,$uid,$redis,$money,$give_money,$mysql,$exp){
	switch($goodsid){
		case 21:
			$happy_num=$redis->data_redis->hGet("hu:{$uid}","301_week_happy_num");//查看当前天数
			if($happy_num==0){
				$redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",6);
				$redis->data_redis->hSet("hu:{$uid}","is_get_week_happy",1);
				$num=6;
				$prop_id=301;
			}else{
				$redis->data_redis->hincrBy("hu:{$uid}","301_week_happy_num",7);
				$num=7;
				$prop_id=301;
			}
			$redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
			break;
		case 22:

			$redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);//增加赠送的金币
			$overflow_num=$redis->data_redis->hGet("hu:{$uid}","302_week_overflow_num");//查看当前天数
			if($overflow_num==0){
				$redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",6);//改变天数
				$redis->data_redis->hSet("hu:{$uid}","is_get_week_overflow",1);//改变可领取状态
				$num=6;
				$prop_id=302;
			}else{
				$redis->data_redis->hincrBy("hu:{$uid}","302_week_overflow_num",7);//改变天数
				$num=7;
				$prop_id=302;
			}
			$last_money=$money+$give_money;
			insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
			$redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
			break;
	}
	return array('num'=>$num,'prop_id'=>$prop_id);

}

//处理礼包充值
function gift_pay($goodsid,$uid,$redis,$exp,$num){
	$porp_s=array(
			'101_gift_num'=>31,
			'102_gift_num'=>32,
			'103_gift_num'=>33,
			'104_gift_num'=>34,
			'105_gift_num'=>35,
			'106_gift_num'=>36,
	);
	$keys=array_search($goodsid,$porp_s);
	if($keys){
		$redis->data_redis->hincrBy("hu:{$uid}",$keys,$num);
		$redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
	}else{
		returnData(array(),588,'商品不存在');
	}

}

//金币礼包
function gift_money($give_money,$mysql,$redis,$uid,$money,$exp){
	$redis->data_redis->hincrBy("hu:{$uid}","money",$give_money);
	$last_money=$money+$give_money;
	insert_moey($uid,$last_money,(int)$give_money,$mysql);//写入金币变化
	$redis->data_redis->hincrBy("hu:{$uid}","exp",$exp);
}
function insert_moey($uid,$last_money,$give_money,$mysql){
	//var_dump($give_money);
	$info =array();
	$info['type'] = '6';
	$info['uid']    = $uid;
	$info['money']  = $last_money;
	$info['change_money'] = +$give_money;
	$info['create_time']  = time();
	$mysql->insert("money_change_rec",$info);//写入钻石变化表；
}

function returnData($data, $ret = 0, $desc = '') {
			$response['ret'] = $ret;
			$response['desc'] = $desc;

			//$this->response['action'] = $this->tag;
			$response['data'] = $data;	
			echo json_encode($response);
			return;
}

function http_post_data($url, $data_string) {
	
		  $curl_handle=curl_init();
		  curl_setopt($curl_handle,CURLOPT_URL, $url);
		  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER, true);
		  curl_setopt($curl_handle,CURLOPT_HEADER, 0);
		  curl_setopt($curl_handle,CURLOPT_POST, true);
		  curl_setopt($curl_handle,CURLOPT_POSTFIELDS, $data_string);
		  curl_setopt($curl_handle,CURLOPT_SSL_VERIFYHOST, 0);
		  curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER, 0);
		  $response_json =curl_exec($curl_handle);
		  $response =json_decode($response_json);
		  curl_close($curl_handle);
		  return $response;
}

do_trade();

?>
